package com.woniuxy.kaer.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.woniuxy.kaer.commons.util.Data;
import com.woniuxy.kaer.commons.util.PageInfo;
import com.woniuxy.kaer.commons.util.Result;
import com.woniuxy.kaer.redis.util.RedisKey;
import com.woniuxy.kaer.service.config.WebSocketServer;
import com.woniuxy.kaer.service.dto.*;
import com.woniuxy.kaer.service.entity.*;
import com.woniuxy.kaer.service.mapper.*;
import com.woniuxy.kaer.service.param.MakeServiceOrderParam;
import com.woniuxy.kaer.service.param.RateOrderParam;
import com.woniuxy.kaer.service.param.ReplyCommentParam;
import com.woniuxy.kaer.service.param.SelectOrderParam;
import com.woniuxy.kaer.service.service.ServiceOrderService;
import com.woniuxy.kaer.tenants.dto.FoundInfoDto;
import com.woniuxy.kaer.tenants.dto.ShopInfoDto;
import com.woniuxy.kaer.tenants.feign.TenantsFeignClient;
import com.woniuxy.kaer.tenants.from.UpdateShopScoreFrom;
import com.woniuxy.kaer.user.UserInfoFeignClient;
import com.woniuxy.kaer.user.dto.UserInfoDTO;
import org.redisson.api.RLock;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年02月17日
 */
@Service
public class ServiceOrderServiceImpl extends ServiceImpl<ServiceOrderMapper, ServiceOrder> implements ServiceOrderService {

    @Resource
    private ServiceOrderMapper serviceOrderMapper;
    @Resource
    private TenantsFeignClient tenantsFeignClient;
    @Resource
    private ServiceProjectMapper serviceProjectMapper;
    @Resource
    private ServiceRealMapper serviceRealMapper;
    @Resource
    private ServiceEvaluateMapper serviceEvaluateMapper;
    @Resource
    private ServiceRealDetailMapper serviceRealDetailMapper;
    @Resource
    private ConsumablesMapper consumablesMapper;
    @Resource
    private ServiceBaseMapper serviceBaseMapper;
    @Resource
    private ServiceProcessesMapper serviceProcessesMapper;
    @Resource
    private AlipayClient alipayClient;
    @Value("${alipay.config.publicKey}")
    private String publicKey;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ServiceOrderLogMapper serviceOrderLogMapper;
    @Resource
    private UserInfoFeignClient userInfoFeignClient;

    @Override
    public OrderMessageDto makeServiceOrder(MakeServiceOrderParam param) throws Exception {
        System.out.println(param.getServiceBaseId());
        //ServiceBase serviceBase = serviceBaseMapper.selectById(param.getServiceBaseId());
        QueryWrapper<ServiceBase> serviceBaseQueryWrapper = new QueryWrapper<>();
        serviceBaseQueryWrapper.eq("service_base_id",param.getServiceBaseId());
        ServiceBase serviceBase = serviceBaseMapper.selectOne(serviceBaseQueryWrapper);
        if(null==serviceBase){
            throw new Exception("服务类别不存在");
        }
        QueryWrapper<ServiceProject> serviceProjectQueryWrapper1 = new QueryWrapper<>();
        serviceProjectQueryWrapper1.eq("service_base_id",param.getServiceBaseId());
        List<ServiceProject> serviceProjects1 = serviceProjectMapper.selectList(serviceProjectQueryWrapper1);
        BigDecimal  orderPrice =null;
        for (ServiceProject serviceProject : serviceProjects1) {
            orderPrice = orderPrice.add(serviceProject.getLaborHours());
            QueryWrapper<Consumables> consumablesQueryWrapper = new QueryWrapper<>();
            consumablesQueryWrapper.eq("service_project_id",serviceProject.getServiceProjectId());
            List<Consumables> consumables = consumablesMapper.selectList(consumablesQueryWrapper);
            if(null!=consumables&&consumables.size()>0){
                for (Consumables consumable : consumables) {
                    orderPrice = orderPrice.add(consumable.getConsumablesPrice());
                }
            }
        }
        Result<ShopInfoDto> result = tenantsFeignClient.getShopInfoByShopId(serviceBase.getShopId());
        if (null==result.getData()){
            throw new Exception("店铺不存在");
        }
        ServiceOrder serviceOrder = BeanUtil.toBean(param, ServiceOrder.class);
        serviceOrder.setShopId(serviceBase.getShopId());
        serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_APPOINTMENT);
        serviceOrder.setCreateTime(LocalDateTime.now().toString());
        Snowflake snowflake1 = new Snowflake(1, 1);
        String prefix = snowflake1.nextIdStr();
        serviceOrder.setTotalPrice(orderPrice);
        serviceOrder.setServiceOrderId(prefix);
        serviceOrder.setPayState(Data.SERVICE_ORDER_STATE_NOT_PAY);
        OrderMessageDto orderMessageDto = BeanUtil.toBean(serviceOrder, OrderMessageDto.class);
        serviceOrderMapper.insert(serviceOrder);

        QueryWrapper<ServiceProject> serviceProjectQueryWrapper = new QueryWrapper<>();
        serviceProjectQueryWrapper.eq("service_base_id",serviceOrder.getServiceBaseId());
        List<ServiceProject> serviceProjects = serviceProjectMapper.selectList(serviceProjectQueryWrapper);
        for (ServiceProject serviceProject : serviceProjects) {
            ServiceReal serviceReal = new ServiceReal();
            serviceReal.setServiceRealName(serviceProject.getServiceProjectName());
            serviceReal.setServiceOrderId(prefix);
            serviceReal.setRealHourlyRate(serviceProject.getLaborHours());
            serviceRealMapper.insert(serviceReal);
            QueryWrapper<Consumables> consumablesQueryWrapper = new QueryWrapper<>();
            consumablesQueryWrapper.eq("service_project_id",serviceProject.getServiceProjectId());
            List<Consumables> consumables = consumablesMapper.selectList(consumablesQueryWrapper);
            for (Consumables consumable : consumables) {
                ServiceRealDetail serviceRealDetail = new ServiceRealDetail();
                serviceRealDetail.setServiceRealId(serviceReal.getServiceRealId());
                serviceRealDetail.setMaterialName(consumable.getConsumablesName());
                serviceRealDetail.setMaterialNum(consumable.getConsumablesNum());
                serviceRealDetail.setMaterialPrice(consumable.getConsumablesPrice());
                serviceRealDetailMapper.insert(serviceRealDetail);
            }
            ServiceProcesses serviceProcesses = new ServiceProcesses();
            serviceProcesses.setServiceOrderId(prefix);
            serviceProcesses.setProcessesName(serviceProject.getServiceProjectName());
            serviceProcesses.setSerialNumber(serviceProject.getSerialNumber());
            serviceProcesses.setServiceRealId(serviceReal.getServiceRealId());
            serviceProcesses.setCurrentOperator(serviceBase.getServiceBaseFounder());
            serviceProcesses.setState(Data.SERVICE_PROCESSES_STATE_NOT_COMPLETE);//流程0.未完成1.已完成
            serviceProcessesMapper.insert(serviceProcesses);
            // 向商户发送预约成功的消息
            String shopId = String.valueOf(serviceBase.getShopId()); // 获取商户ID
            String message = "用户 " + param.getUserId() + " 预约了服务订单，订单ID: " + orderMessageDto.getServiceOrderId();
            //WebSocketServer.sendToShop(shopId, message);
            WebSocketServer.sendInfo(message, shopId);
        }
        //动态生成定时任务
        rabbitTemplate.convertAndSend("","judge_order_expired_queue",serviceOrder.getServiceOrderId());
        //日志的记录
        ServiceOrderLog serviceOrderLog = new ServiceOrderLog();
        serviceOrderLog.setOptionType("预约服务");
        serviceOrderLog.setOptionTime(LocalDateTime.now());
        serviceOrderLog.setServiceOrderId(serviceOrder.getServiceOrderId());
        serviceOrderLog.setOperator("用户"+param.getUserId());
        serviceOrderLogMapper.insert(serviceOrderLog);
        return orderMessageDto;
    }

    @Override
    public void takeServiceOrder(String serviceOrderId, Integer founderId) {
        System.out.println(serviceOrderId);
        //ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("service_order_id",serviceOrderId);
        ServiceOrder serviceOrder = serviceOrderMapper.selectOne(serviceOrderQueryWrapper);
        if(null==serviceOrder){
            throw new RuntimeException("订单不存在");
        }
        if(Data.SERVICE_ORDER_STATE_APPOINTMENT!=serviceOrder.getServiceOrderState()){
            throw new RuntimeException("订单状态异常");
        }
        serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_ACCEPT);
        serviceOrderMapper.updateById(serviceOrder);

       //日志记录
        ServiceOrderLog serviceOrderLog = new ServiceOrderLog();
        serviceOrderLog.setOptionType("预约服务");
        serviceOrderLog.setOptionTime(LocalDateTime.now());
        serviceOrderLog.setServiceOrderId(serviceOrder.getServiceOrderId());
        serviceOrderLog.setOperator("用户"+founderId);
        serviceOrderLogMapper.insert(serviceOrderLog);
    }

    @Override
    public String pay(String serviceOrderId, Integer userId) throws Exception {
//        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("service_order_id",serviceOrderId);
        ServiceOrder serviceOrder = serviceOrderMapper.selectOne(serviceOrderQueryWrapper);
        if (null==serviceOrder){
            throw new Exception("订单不存在");
        }
        if(Data.SERVICE_ORDER_STATE_PROCESSING!=serviceOrder.getServiceOrderState()){
            throw new Exception("订单状态异常");
        }
        //修改支付订单状态
        serviceOrder.setPayState(Data.SERVICE_ORDER_STATE_PAY);
        serviceOrderMapper.updateById(serviceOrder);
        //拼接支付宝所需参数
//        HashMap<String, Object> params = new HashMap<>();
//        params.put("out_trade_no",serviceOrderId);
//        params.put("total_amount",serviceOrder.getTotalPrice());
//        params.put("subject","kaer养车");
//        params.put("body","服务订单支付");
//        params.put("product_code","FAST_INSTANT_TRADE_PAY");
//        ZoneId zoneId = ZoneId.systemDefault();
//        ZonedDateTime zonedDateTime = serviceOrder.getAppointmentTime().atZone(zoneId);
//        long timeStamp = zonedDateTime.toInstant().toEpochMilli();
//        Date date = new Date(timeStamp + 15 * 60 * 1000);
//        String expire = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
//        params.put("time_expire",expire);
//        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        //设置参数
//        request.setBizContent(JSONUtil.toJsonStr(params));
//        //同步回调
//        request.setReturnUrl("http://www.woniuxy.com");
//        //异步回调
//        request.setNotifyUrl("http://jnnf5s.natappfree.cc/service/serviceOrder/notify");
//        //发送请求i
//        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
//
//        if(response.isSuccess()){
//            CorrelationData messageId = new CorrelationData(UUID.randomUUID().toString());
//            rabbitTemplate.convertAndSend("","waiting_check_pay_queue",serviceOrderId,messageId);
//            return response.getBody();
//        }
//        throw new Exception("发起支付失败");
        return "支付成功";
    }

    @Override
    public void handleOrder(Map<String, String> params) throws Exception {
        System.out.println("公钥:"+publicKey);
        //验签
        //System.out.println("params"+params);
        System.out.println(2222);
        System.out.println("params"+params);
        boolean b = AlipaySignature.rsaCheckV1(params, publicKey, "utf-8", "RSA2");
        if(b){
            //获取订单编号以及支付的时间

            String serviceOrderId = params.get("out_trade_no");
            String tradeStatus = params.get("trade_status");
            System.out.println(params);
            System.out.println(tradeStatus);
            if("TRADE_SUCCESS".equals(tradeStatus)){
                String payTime = params.get("gmt_payment");
                System.out.println(payTime);
                //更新订单的状态和商品的库存
                System.out.println("回调里，调用过呢更改支付状态方法");
                updateOrder(serviceOrderId,payTime);
            }
        }
    }

    public void updateOrder(String serviceOrderId,String payTime){
        //查询订单详情
        System.out.println("支付宝回调");
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        if(serviceOrder!=null){
//            throw new Exception("订单不存在");
            if(serviceOrder.getPayState()==Data.SERVICE_ORDER_STATE_NOT_PAY){
            //if(orderInfo.getOrderState()==Data.ORDER_STATE_NOPAY){
                System.out.println("更新订单的支付状态，支付时间");
                serviceOrder.setPayState(Data.SERVICE_ORDER_STATE_PAY);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDate = LocalDateTime.parse(payTime, formatter);
                serviceOrder.setPayTime(localDate);
                serviceOrderMapper.updateById(serviceOrder);
                }
            }
        }

    @Override
    public void cancelOrder(String serviceOrderId) throws Exception {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        if(serviceOrder!=null){
//            throw new Exception("订单不存在");
            if(serviceOrder.getPayState()==Data.ORDER_PAY_STATE_NOPAY){
                serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_CANCEL);
                serviceOrderMapper.updateById(serviceOrder);

            }
        }
    }

    @Override
    public void rateOrder(RateOrderParam param) throws Exception {
        Result<UserInfoDTO> result1 = userInfoFeignClient.selectSelf(param.getUserId());
        UserInfoDTO userInfoDTO = result1.getData();
        if(userInfoDTO==null){
            throw new Exception("用户不存在");
        }
        Result<UserInfoDTO> userInfoDTOResult = userInfoFeignClient.selectSelf(param.getUserId());;
        //ServiceOrder serviceOrder = serviceOrderMapper.selectById(param.getServiceOrderId());
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("service_order_id",param.getServiceOrderId());
        ServiceOrder serviceOrder = serviceOrderMapper.selectOne(serviceOrderQueryWrapper);

        if(serviceOrder==null){
            throw new Exception("订单不存在");
        }
        Result<ShopInfoDto> result = tenantsFeignClient.getShopInfoByShopId(serviceOrder.getShopId());
        if(result.getData()==null){
            throw new Exception("店铺不存在");
        }
        if(serviceOrder.getServiceOrderState()!=Data.SERVICE_ORDER_STATE_COMPLETE&&serviceOrder.getPayState()!=Data.SERVICE_ORDER_STATE_PAY){
            throw new Exception("订单未完成或订单支付");
        }
        serviceOrder.setEvaluateScore(param.getServiceOrderEvaluateScore());
        ServiceEvaluate serviceEvaluate = BeanUtil.toBean(param, ServiceEvaluate.class);
        serviceEvaluate.setUserName(userInfoDTO.getUserName());
        serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_RATED);
        serviceOrderMapper.updateById(serviceOrder);
        serviceEvaluateMapper.insert(serviceEvaluate);
        //查询redis中存储的店铺评分，没有的话从数据库中查询
        rabbitTemplate.convertAndSend("","shop_points_calculated_queue",param.getServiceOrderId());

        //日志记录
        ServiceOrderLog serviceOrderLog = new ServiceOrderLog();
        serviceOrderLog.setServiceOrderId(param.getServiceOrderId());
        serviceOrderLog.setOperator(userInfoDTO.getUserName());
        serviceOrderLog.setOptionTime(LocalDateTime.now());
        serviceOrderLog.setOptionType("评价订单");
        serviceOrderLogMapper.insert(serviceOrderLog);

    }


    @Override
    public void userConfirmOrderFinish(String serviceOrderId, Integer userId) throws Exception {
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("service_order_id",serviceOrderId);
        ServiceOrder serviceOrder = serviceOrderMapper.selectOne(serviceOrderQueryWrapper);
       // ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        if(serviceOrder==null){
            throw new Exception("订单不存在");
        }
        if(serviceOrder.getPayState()!=Data.SERVICE_ORDER_STATE_PAY){
            throw new Exception("订单未支付");
        }
        QueryWrapper<ServiceProcesses> serviceProcessesQueryWrapper = new QueryWrapper<>();
        serviceProcessesQueryWrapper.eq("service_order_id",serviceOrderId);
        List<ServiceProcesses> serviceProcesses = serviceProcessesMapper.selectList(serviceProcessesQueryWrapper);
        for (ServiceProcesses serviceProcess : serviceProcesses) {
            if(serviceProcess.getState()!=Data.SERVICE_PROCESSES_STATE_COMPLETE){
                throw new Exception("订单未完成");
            }
        }
        serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_COMPLETE);
        serviceOrderMapper.updateById(serviceOrder);
    }

    @Override
    public void OrderTimeout(String serviceOrderId, Integer founderId) throws Exception {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        Result<FoundInfoDto> result = tenantsFeignClient.getFounderById(founderId);
        FoundInfoDto founderInfoDto = result.getData();
        if(founderInfoDto==null){
            throw new Exception("商家不存在");
        }
        if(founderInfoDto.getFounderState()!=Data.FOUNDER_STATE_NORMAL){
            throw new Exception("商家状态异常");
        }
        if(serviceOrder==null){
            throw new Exception("订单不存在");
        }
        if(serviceOrder.getServiceOrderState()!=Data.SERVICE_ORDER_STATE_CONFIRM){
            throw new Exception("订单状态异常");
        }
        serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_CANCEL);
        serviceOrderMapper.updateById(serviceOrder);
        //日志记录
        ServiceOrderLog serviceOrderLog = new ServiceOrderLog();
        serviceOrderLog.setServiceOrderId(serviceOrderId);
        serviceOrderLog.setOperator(founderInfoDto.getDounderName());
        serviceOrderLog.setOptionTime(LocalDateTime.now());
        serviceOrderLog.setOptionType("超时订单的取消");
        serviceOrderLogMapper.insert(serviceOrderLog);

    }

    //用户确定项目
    @Override
    public void userConfirmOrder(String serviceOrderId,Integer userId) throws Exception {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        if (null==serviceOrder){
            throw new Exception("订单不存在");
        }
        if(serviceOrder.getServiceOrderState()!=Data.SERVICE_ORDER_STATE_ACCEPT){
            throw new Exception("订单状态异常");
        }
        serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_CONFIRM);
        serviceOrderMapper.updateById(serviceOrder);
    }

    @Override
    public OrderInfoDto getServiceOrderById(String serviceOrderId) throws Exception {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderId);
        if(null==serviceOrder){
            throw new Exception("订单不存在");
        }
        OrderInfoDto orderInfoDto = BeanUtil.toBean(serviceOrder, OrderInfoDto.class);
        return orderInfoDto;
    }

    @Override
    public List<OrderInfoDto> getAllServiceOrder(Integer shopId) throws Exception {
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("shop_id",shopId);
        serviceOrderQueryWrapper.eq("service_order_state",Data.SERVICE_ORDER_STATE_APPOINTMENT);
        List<ServiceOrder> serviceOrders = serviceOrderMapper.selectList(serviceOrderQueryWrapper);
        ArrayList<OrderInfoDto> orderInfoDtos = new ArrayList<>();
        for (ServiceOrder serviceOrder : serviceOrders) {
            OrderInfoDto orderInfoDto = BeanUtil.toBean(serviceOrder, OrderInfoDto.class);
            orderInfoDtos.add(orderInfoDto);
        }
        return orderInfoDtos;
    }

    @Override
    public PageInfo getAllServiceOrderByPage(SelectOrderParam param) throws Exception {
        Page<ServiceOrder> serviceOrderPage = new Page<>(param.getPageNum(),param.getPageSize());
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("shop_id",param.getShopId());
        serviceOrderMapper.selectPage(serviceOrderPage, serviceOrderQueryWrapper);
        PageInfo serviceOrderPageInfo = new PageInfo(serviceOrderPage);
        return serviceOrderPageInfo;
    }

    @Override
    public List<OrderInfoDto> getAllServiceOrderByProcessing(Integer shopId, Integer founderId) throws Exception {
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("shop_id",shopId);
        serviceOrderQueryWrapper.eq("service_order_state",Data.SERVICE_ORDER_STATE_PROCESSING);
        serviceOrderQueryWrapper.or();
        serviceOrderQueryWrapper.eq("service_order_state",Data.SERVICE_ORDER_STATE_CONFIRM);
        List<ServiceOrder> serviceOrders = serviceOrderMapper.selectList(serviceOrderQueryWrapper);
        ArrayList<OrderInfoDto> orderInfoDtos = new ArrayList<>();
        for (ServiceOrder serviceOrder : serviceOrders) {
            OrderInfoDto orderInfoDto = BeanUtil.toBean(serviceOrder, OrderInfoDto.class);
            orderInfoDtos.add(orderInfoDto);
        }
        return orderInfoDtos;
    }

    @Override
    public List<OrderInfoDto> getAllServiceOrderByUnpaid(Integer userId) throws Exception {
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("user_id",userId);
        serviceOrderQueryWrapper.ne("service_order_state",Data.SERVICE_ORDER_STATE_CANCEL);//4
        serviceOrderQueryWrapper.ne("service_order_state",Data.SERVICE_ORDER_STATE_APPOINTMENT);//0
        serviceOrderQueryWrapper.ne("service_order_state",Data.SERVICE_ORDER_STATE_ACCEPT);//1
        serviceOrderQueryWrapper.ne("service_order_state",Data.SERVICE_ORDER_STATE_CONFIRM);//2
        serviceOrderQueryWrapper.ne("service_order_state",Data.SERVICE_ORDER_STATE_CANCEL);//5
        List<ServiceOrder> serviceOrders = serviceOrderMapper.selectList(serviceOrderQueryWrapper);
        ArrayList<OrderInfoDto> orderInfoDtos = new ArrayList<>();
        for (ServiceOrder serviceOrder : serviceOrders) {
            OrderInfoDto orderInfoDto = BeanUtil.toBean(serviceOrder, OrderInfoDto.class);
            orderInfoDtos.add(orderInfoDto);
        }
        return orderInfoDtos;
    }

    @Override
    public List<OrderInfoDto> getAllServiceOrderByFinished(Integer userId) throws Exception {
        QueryWrapper<ServiceOrder> serviceOrderQueryWrapper = new QueryWrapper<>();
        serviceOrderQueryWrapper.eq("user_id",userId);
        serviceOrderQueryWrapper.eq("pay_state",Data.SERVICE_ORDER_STATE_PAY);
        serviceOrderQueryWrapper.eq("service_order_state",Data.SERVICE_ORDER_STATE_PROCESSING);
        List<ServiceOrder> serviceOrders = serviceOrderMapper.selectList(serviceOrderQueryWrapper);
        ArrayList<OrderInfoDto> orderInfoDtos = new ArrayList<>();
        for (ServiceOrder serviceOrder : serviceOrders) {
            QueryWrapper<ServiceProcesses> serviceProcessesQueryWrapper = new QueryWrapper<>();
            serviceProcessesQueryWrapper.eq("service_order_id",serviceOrder.getServiceOrderId());
            List<ServiceProcesses> serviceProcesses = serviceProcessesMapper.selectList(serviceProcessesQueryWrapper);
            for (ServiceProcesses serviceProcess : serviceProcesses) {
                if(serviceProcess.getSerialNumber()==serviceProcesses.size()){
                    if(serviceProcess.getState()==Data.SERVICE_PROCESSES_STATE_COMPLETE){
                        OrderInfoDto orderInfoDto = BeanUtil.toBean(serviceOrder, OrderInfoDto.class);
                        orderInfoDtos.add(orderInfoDto);
                    }
                }
            }
            //serviceProcessesMapper
        }
        return orderInfoDtos;
    }

    @Override
    public TodayOrderInfoDto getTodayOrderInfo(Integer founderId) throws Exception {
        Result<ShopInfoDto> result = tenantsFeignClient.getShopInfoByFounderId(founderId);
        ShopInfoDto shopInfoDto = result.getData();
        if(shopInfoDto==null){
            throw new Exception("商户不存在");
        }
        //查询当天的完结订单数量
        Integer takeOrderNum = serviceOrderMapper.getTakeOrderNumByShopId(shopInfoDto.getShopId());
        //查询当天的销售总额
        BigDecimal orderSaleAmount = serviceOrderMapper.getOrderSaleAmountByShopId(shopInfoDto.getShopId());
        //查询当天的预约订单数量
        Integer appointmentOrderNum = serviceOrderMapper.getMakeOrderNumByShopId(shopInfoDto.getShopId());
        TodayOrderInfoDto todayOrderInfoDto = new TodayOrderInfoDto();
        todayOrderInfoDto.setMakeOrderNum(appointmentOrderNum);
        todayOrderInfoDto.setTakeOrderNum(takeOrderNum);
        todayOrderInfoDto.setSaleAmount(orderSaleAmount);
        return todayOrderInfoDto;
    }

    @Override
    public ThreeMonthMerchantStatisticsDto getThreeMonthOrderInfo(Integer founderId) throws Exception {
        Result<ShopInfoDto> result = tenantsFeignClient.getShopInfoByFounderId(founderId);
        ShopInfoDto shopInfoDto = result.getData();
        if(shopInfoDto==null){
            throw new Exception("商户不存在");
        }
        int makeOrderNumByShopId90Days = 0;
        int takeOrderNumByShopId90Days = 0;
        String orderSaleAmountByShopId90Days = "0.00";

        String key = RedisKey.SHOP_ORDER_INFO(shopInfoDto.getShopId());
        if (stringRedisTemplate.hasKey(key)) {
            // 获取下单数量
            Object makeOrderNumObj = stringRedisTemplate.opsForHash().get(key, "makeOrderNumByShopId90Days");
            if (makeOrderNumObj != null) {
                try {
                    makeOrderNumByShopId90Days = Integer.parseInt(makeOrderNumObj.toString());
                } catch (NumberFormatException e) {
                    // 处理转换异常，可根据实际情况进行日志记录或其他处理
                    System.err.println("无法将 makeOrderNumByShopId90Days 转换为整数: " + makeOrderNumObj);
                }
            }

            // 获取接单数量
            Object takeOrderNumObj = stringRedisTemplate.opsForHash().get(key, "takeOrderNumByShopId90Days");
            if (takeOrderNumObj != null) {
                try {
                    takeOrderNumByShopId90Days = Integer.parseInt(takeOrderNumObj.toString());
                } catch (NumberFormatException e) {
                    // 处理转换异常，可根据实际情况进行日志记录或其他处理
                    System.err.println("无法将 takeOrderNumByShopId90Days 转换为整数: " + takeOrderNumObj);
                }
            }

            // 获取销售金额
            Object orderSaleAmountObj = stringRedisTemplate.opsForHash().get(key, "orderSaleAmountByShopId90Days");
            if (orderSaleAmountObj != null) {
                orderSaleAmountByShopId90Days = orderSaleAmountObj.toString();
            }
        }

        ThreeMonthMerchantStatisticsDto threeMonthMerchantStatisticsDto = new ThreeMonthMerchantStatisticsDto();
        threeMonthMerchantStatisticsDto.setMakeOrderThreeMonthNum(makeOrderNumByShopId90Days);
        threeMonthMerchantStatisticsDto.setTakeOrderThreeMonthNum(takeOrderNumByShopId90Days);
        threeMonthMerchantStatisticsDto.setSaleAmountThreeMonth(orderSaleAmountByShopId90Days);
        return threeMonthMerchantStatisticsDto;
    }

    @Override
    public List<ServiceAndServiceRealDetailDto> getAllServiceAndConsumablesByServiceOrderId(String serviceOrderId) throws Exception {
        ArrayList<ServiceAndServiceRealDetailDto> serviceAndServiceRealDetailDtos = new ArrayList<>();
        //通过订单Id查询订单项目
        QueryWrapper<ServiceReal> serviceRealQueryWrapper = new QueryWrapper<>();
        serviceRealQueryWrapper.eq("service_order_id",serviceOrderId);
        List<ServiceReal> serviceReals = serviceRealMapper.selectList(serviceRealQueryWrapper);
        for (ServiceReal serviceReal : serviceReals) {
            //通过订单项目Id查询订单项目详情
            ServiceAndServiceRealDetailDto serviceAndServiceRealDetailDto = BeanUtil.toBean(serviceReal, ServiceAndServiceRealDetailDto.class);
            QueryWrapper<ServiceRealDetail> serviceRealDetailQueryWrapper = new QueryWrapper<>();
            serviceRealDetailQueryWrapper.eq("service_real_id",serviceReal.getServiceRealId());
            List<ServiceRealDetail> serviceRealDetails = serviceRealDetailMapper.selectList(serviceRealDetailQueryWrapper);
            for (ServiceRealDetail serviceRealDetail : serviceRealDetails) {
                //查询订单项目耗材
                ServiceRealDetailDto serviceRealDetailDto = BeanUtil.toBean(serviceRealDetail, ServiceRealDetailDto.class);
                serviceAndServiceRealDetailDto.getServiceRealDetailDtoList().add(serviceRealDetailDto);
            }
            serviceAndServiceRealDetailDtos.add(serviceAndServiceRealDetailDto);
        }
        return serviceAndServiceRealDetailDtos;
    }

    @Override
    public void replyComment(ReplyCommentParam replyCommentParam) throws Exception {
        QueryWrapper<ServiceEvaluate> serviceEvaluateQueryWrapper = new QueryWrapper<>();
        serviceEvaluateQueryWrapper.eq("service_order_id",replyCommentParam.getServiceOrderId());
        ServiceEvaluate serviceEvaluate = serviceEvaluateMapper.selectOne(serviceEvaluateQueryWrapper);
        serviceEvaluate.setComment(replyCommentParam.getComment());
        serviceEvaluateMapper.updateById(serviceEvaluate);
    }

}
